import mongodbHandle from '../handle/mongodbHandle'
import * as moment from 'moment'
import app from '../app'
import { PlayerModel } from 'src/core/model/playerModel'
import utils from '../serverCore/utils'
import redisHandle from './redisHandle'
import * as schedule from 'node-schedule'
import * as cluster from 'cluster'

var ObjectId = require('mongodb').ObjectId;

let randDiamonds = [450, 300, 200, 150]
var RankDay = -300
class RankHandle {
    powerRankData: any
    powerRankArray: any
    abyssRankData: any
    abyssRankArray: any
    equipmentPowerRankData: any
    equipmentPowerRankArray: any
    arenaRankData: any
    arenaRankArray: any
    mapProgressRankData: any
    mapProgressRankArray: any
    worldBossRankData: any
    worldBossRankArray: any
    run: boolean
    constructor() {
        this.powerRankData = {} //总战斗力
        this.powerRankArray = {}
        this.arenaRankData = {}
        this.arenaRankArray = {}
        this.mapProgressRankData = {}
        this.mapProgressRankArray = {}
        this.worldBossRankData = {}
        this.worldBossRankArray = {}
        this.equipmentPowerRankData = {}
        this.equipmentPowerRankArray = {}
        this.run = false
    }
    init = async () => {
        // await redisHandle.init()
        if (app.env !== 'adminPro') {
            setTimeout(async () => {
                await this.initArenaRank()
                await this.initPowerRank()
                await this.initMapProgressRank()
                await this.initAbyssProgressRank()
                // rankHandle.initEquipmentPowerRank()
            }, 3000)
            setInterval(async () => {
                await this.initPowerRank()
                await this.initMapProgressRank()
                await this.initArenaRank()
                await this.initAbyssProgressRank()
            }, 15 * 60 * 1000)
        }
    }
    resetRank = async () => {
        console.log('resetRank')
        await this.initPowerRank()
        await this.initMapProgressRank()
        await this.initArenaRank()
        await this.initAbyssProgressRank()
        console.log('resetRankEnd')
    }

    getServerList = async () => {
        let docs = await mongodbHandle.serverDao.find({
            active: true
        })
        let serverList = {}
        for (let i = 0; i < docs.length; i++) {
            let serverID = docs[i].newServerID
            serverList[serverID] = true
        }
        let servers: number[] = []
        Object.keys(serverList).forEach((item, i) => {
            servers[i] = Number(item)
        })
        return servers
    }
    initPowerRank = async () => {
        console.log('initPowerRank')
        this.powerRankData = {}
        this.powerRankArray = {}
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.powerRankArray[serverID] = {}
            this.powerRankData[serverID] = {}

            this.powerRankArray[serverID] = []
            this.powerRankData[serverID] = {}
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "cheat": false,
                "totalPower": {
                    $gt: 10000
                },
            }, {
                "totalPower": -1
            }, 0, 1000)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.totalPower,
                    name: doc.name,
                }
                this.powerRankArray[serverID].push(data);
                this.powerRankData[serverID][doc._id.toString()] = data
            }
            console.log('powerRankArray' + serverID, this.powerRankArray[serverID].length)

        }
    }


    initArenaRank = async () => {
        console.log('initArenaRank')
        this.arenaRankData = {}
        this.arenaRankArray = {}
        let serverList = await this.getServerList()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.arenaRankArray[serverID] = {}
            this.arenaRankData[serverID] = {}

            this.arenaRankArray[serverID] = []
            this.arenaRankData[serverID] = {}
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "arenaScore": {
                    $gte: 140 * 100000000
                },
            }, {
                "arenaScore": -1
            }, 0, 1000)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.arenaScore,
                    name: doc.name
                }
                this.arenaRankArray[serverID].push(data);
                this.arenaRankData[serverID][doc._id.toString()] = data
            }
            console.log('initArenaRank' + serverID, this.arenaRankArray[serverID].length)

        }
    }

    initMapProgressRank = async () => {
        console.log('initMapProgressRank')
        this.mapProgressRankData = {}
        this.mapProgressRankArray = {}
        let serverList = await this.getServerList()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.mapProgressRankArray[serverID] = []
            this.mapProgressRankData[serverID] = {}
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "mapProgressMax": {
                    $gte: 100
                },
            }, {
                "mapProgressMax": -1
            }, 0, 1000)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.mapProgressMax,
                    name: doc.name,
                }
                this.mapProgressRankArray[serverID].push(data);
                this.mapProgressRankData[serverID][doc._id.toString()] = data
            }
            console.log('initMapProgressRank_' + serverID, this.mapProgressRankArray[serverID].length)
        }
    }

    initAbyssProgressRank = async () => {
        console.log('initAbyssProgressRank')
        this.abyssRankData = {}
        this.abyssRankArray = {}
        let serverList = await this.getServerList()
        let dayTime = moment().startOf('day').valueOf()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.abyssRankArray[serverID] = []
            this.abyssRankData[serverID] = {}
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "abyssProgress": {
                    $gte: 10
                },
            }, {
                "abyssProgress": -1
            }, 0, 1000)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.abyssProgress,
                    name: doc.name,
                }
                this.abyssRankArray[serverID].push(data);
                this.abyssRankData[serverID][doc._id.toString()] = data
            }
            console.log('initAbyssProgressRank_' + serverID, this.abyssRankArray[serverID].length)
        }

    }

    getPowerRankByPID(serverID, pid, phone) {

        if (this.powerRankData && this.powerRankData[serverID] && this.powerRankData[serverID]) {
            let d = this.powerRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getPowerRank(serverID, phone) {
        if (this.powerRankArray && this.powerRankArray[serverID] && this.powerRankArray[serverID]) {
            return this.powerRankArray[serverID]
        } else {
            return []
        }
    }

    getArenaRankByPID(serverID, pid, phone) {
        if (this.arenaRankData && this.arenaRankData[serverID]) {
            let d = this.arenaRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getArenaRank(serverID, phone) {
        if (this.arenaRankArray && this.arenaRankArray[serverID] && this.arenaRankArray[serverID]) {
            return this.arenaRankArray[serverID]
        } else {
            return []
        }
    }

    getMapProgressRank = (serverID, phone) => {
        if (this.mapProgressRankArray && this.mapProgressRankArray[serverID] && this.mapProgressRankArray[serverID]) {
            return this.mapProgressRankArray[serverID]
        } else {
            return []
        }
    }

    getMapProgressRankByPID = (serverID, pid, phone) => {
        if (this.mapProgressRankData && this.mapProgressRankData[serverID] && this.mapProgressRankData[serverID]) {
            let d = this.mapProgressRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getAbyssProgressRank = (serverID, phone) => {
        if (this.abyssRankArray && this.abyssRankArray[serverID] && this.abyssRankArray[serverID]) {
            return this.abyssRankArray[serverID]
        } else {
            return []
        }
    }

    getAbyssProgressRankByPID = (serverID, pid, phone) => {
        if (this.abyssRankData && this.abyssRankData[serverID] && this.abyssRankData[serverID]) {
            let d = this.abyssRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }


    schedule = () => {
        console.log('schedule任务')
        schedule.scheduleJob('0 0 19 * * *', async () => {
            rankHandle.run = true
            await this.createMapProgressRankReward()
            rankHandle.run = false
        });
        schedule.scheduleJob('0 0 20 * * *', async () => {
            rankHandle.run = true
            await this.createPowerRankReward()
            rankHandle.run = false
        });
        schedule.scheduleJob('0 0 21 * * *', async () => {
            rankHandle.run = true
            await this.createArenaRankReward()
            rankHandle.run = false
        });
        schedule.scheduleJob('0 0 22 * * *', async () => {
            rankHandle.run = true
            await this.createAbyssRankReward()
            rankHandle.run = false
        });
    }


    createMapProgressRankReward = async () => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]

            let length = size
            let page = 0
            let players = []
            console.log('冒险奖励' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "mapProgressMax": {
                        $gt: 100
                    },
                }, {
                    "mapProgressMax": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()

            for (let i = 0; i < players.length; i++) {
                let rank = i
                let diamond = 150 - i * 1
                if (diamond < 50) {
                    diamond = 50
                }
                let vipExp = 5 - i * 1
                if (vipExp < 3) {
                    vipExp = 3
                }
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank < 3) {
                        diamond = randDiamonds[rank]
                    }
                    // 200021 蓝色英雄宝箱 200022 红色英雄宝箱
                    let heroBoxID1 = 200021
                    let heroBoxID2 = 200022
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}地图关卡排名第${rank + 1}奖励`, [["diamond", diamond + 50], [heroBoxID2, 3], ["vipExp", vipExp]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}地图关卡排名第${rank + 1}奖励`, [["diamond", diamond], [heroBoxID2, 2], ["vipExp", vipExp]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}地图关卡排名第${rank + 1}奖励`, [["diamond", diamond], [heroBoxID1, 3], ["vipExp", 3]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}地图关卡排名第${rank + 1}奖励`, [["diamond", diamond], [heroBoxID1, 2], ["vipExp", 2]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}地图关卡排名第${rank + 1}奖励`, [["diamond", diamond], [heroBoxID1, 2], ["vipExp", 2]], null)
                    }
                }
                if (i % 200 == 0) {
                    console.log(i)
                    await utils.setTimeout(20)
                }
            }

        }
        console.log('冒险奖励')
    }


    createPowerRankReward = async () => {
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            console.log('战斗力' + serverID + '服')

            let length = size
            let page = 0
            let players = []
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "totalPower": {
                        $gt: 10000
                    },
                }, {
                    "totalPower": -1
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let diamond = 150 - i * 2
                if (diamond < 50) {
                    diamond = 50
                }
                let itemAmount = 20 - i * 1
                let vipExp = 5 - i * 1
                if (vipExp < 3) {
                    vipExp = 3
                }
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank < 3) {
                        diamond = randDiamonds[rank]
                    }
                    // 200031 秘银沙漏 200032 黄金沙漏
                    let itemID1 = 200031
                    let itemID2 = 200032
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}奖励`, [["diamond", diamond + 50], [itemID2, 2], ["vipExp", vipExp]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}奖励`, [["diamond", diamond], [itemID2, 1], ["vipExp", vipExp]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}奖励`, [["diamond", diamond], [itemID1, 1], ["vipExp", 3]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}奖励`, [["diamond", diamond], [itemID1, 1], ["vipExp", 2]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}奖励`, [["diamond", diamond], [itemID1, 1], ["vipExp", 2]], null)
                    }
                }
                if (i % 200 == 0) {
                    console.log(i)
                    await utils.setTimeout(20)
                }

            }

        }
        console.log('战斗力结束')
    }

    createArenaRankReward = async () => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]

            let length = size
            let page = 0
            let players = []
            console.log('竞技场奖励' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "arenaScore": {
                        $gt: 140 * 100000000
                    },
                }, {
                    "arenaScore": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let diamond = 150 - i * 2
                if (diamond < 50) {
                    diamond = 50
                }
                let vipExp = 5 - i * 1
                if (vipExp < 3) {
                    vipExp = 3
                }
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank < 3) {
                        diamond = randDiamonds[rank]
                    }
                    // 200024 蓝色英雄秘宝 200025 红色英雄秘宝
                    let itemID1 = 200023
                    let itemID2 = 200024
                    let itemID3 = 200025
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", diamond + 50], [itemID3, 3], ["vipExp", vipExp]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", diamond], [itemID3, 2], ["vipExp", vipExp]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", diamond], [itemID2, 3], ["vipExp", vipExp]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", diamond], [itemID2, 2], ["vipExp", vipExp]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", diamond], [itemID2, 2], ["vipExp", vipExp]], null)
                    }
                }
                if (i % 200 == 0) {
                    console.log(i)
                    await utils.setTimeout(20)
                }
            }


        }
        console.log('竞技场奖励结束')
    }


    createAbyssRankReward = async () => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let phones = ["android", "ios"]
        let dayTime = moment().startOf('day').valueOf()
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]

            let length = size
            let page = 0
            let players = []
            console.log('深渊奖励' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "abyssProgress": {
                        $gt: 10
                    },
                }, {
                    "abyssProgress": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            // 200033木制金币宝箱 200034 铁质金币宝箱
            let itemID1 = 200033
            let itemID2 = 200034
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let diamond = 200 - i * 2
                if (diamond < 50) {
                    diamond = 50
                }
                let vipExp = 5 - i * 1
                if (vipExp < 3) {
                    vipExp = 3
                }
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank < 3) {
                        diamond = randDiamonds[rank]
                    }
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}恶魔塔排名第${rank + 1}奖励`, [["diamond", diamond], [itemID2, 3], ["vipExp", vipExp]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}恶魔塔排名第${rank + 1}奖励`, [["diamond", diamond], [itemID2, 2], ["vipExp", vipExp]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}恶魔塔排名第${rank + 1}奖励`, [["diamond", diamond], [itemID1, 3], ["vipExp", vipExp]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}恶魔塔排名第${rank + 1}奖励`, [["diamond", diamond], [itemID1, 2], ["vipExp", vipExp]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}恶魔塔排名第${rank + 1}奖励`, [["diamond", diamond], [itemID1, 2], ["vipExp", vipExp]], null)
                    }
                }
                if (i % 200 == 0) {
                    console.log(i)
                    await utils.setTimeout(20)
                }
            }


        }
        console.log('秘境奖励结束')
    }




}

let rankHandle = new RankHandle()
export default rankHandle

